package com.lou;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;

public class DateUtil {
    // 常用日期格式
    public static final DateTimeFormatter DATE_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
    public static final DateTimeFormatter DATETIME_FORMAT = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    public static final DateTimeFormatter DATETIME_FORMAT_ = DateTimeFormatter.ofPattern("yyyy-MM-dd-HH-mm-ss");
    // Date 转 LocalDate
    public static LocalDate toLocalDate(Date date) {
        return date.toInstant().atZone(java.time.ZoneId.systemDefault()).toLocalDate();
    }

    // LocalDate 转 String
    public static String format(LocalDate date) {
        return date.format(DATE_FORMAT);
    }

    // LocalDate 转 String
    public static String format(LocalDateTime date ,DateTimeFormatter format) {
        return date.format(format);
    }

    // LocalDateTime 转 String
    public static String format(LocalDateTime datetime) {
        return datetime.format(DATETIME_FORMAT);
    }

    // String 转 LocalDate
    public static LocalDate parseDate(String dateStr) {
        return LocalDate.parse(dateStr, DATE_FORMAT);
    }

    // 计算两个日期之间的天数差
    public static long daysBetween(LocalDate start, LocalDate end) {
        return ChronoUnit.DAYS.between(start, end);
    }

    // 获取当前日期时间
    public static LocalDateTime now() {
        return LocalDateTime.now();
    }

    // 示例：计算年龄
    public static int calculateAge(LocalDate birthDate) {
        return birthDate.until(LocalDate.now()).getYears();
    }
}